package xyc.sjxy.exam.controller;

import xyc.sjxy.exam.pojo.Users;
import xyc.sjxy.exam.service.UserService;
import xyc.sjxy.exam.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@WebServlet(value = "/user/login")
public class UserController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取浏览器请求的参数：用户名和密码
        String userName = req.getParameter("userName");
        String userPwd = req.getParameter("userPwd");
        //调用service层的方法login（）验证用户身份
        boolean flag = false;
        try {
            flag = userService.login(userName, userPwd);
            if (flag) {
                //验证通过
                Users loginInfo = new Users();
                loginInfo.setUserName(userName);
                loginInfo.setUserPwd(userPwd);
                //将它放置到session中
                req.getSession().setAttribute("loginInfo",loginInfo);
                //重定向到userList.jsp页面
                //resp.sendRedirect(req.getContextPath()+"/jsp/userList.jsp");
                //调用 service层方法getAll（）获取所有用户的信息
                List<Users> users = userService.getAll();
                req.setAttribute("users",users);
                req.getRequestDispatcher("/jsp/userList.jsp").forward(req,resp);

            } else {
                resp.getWriter().write("用户名或密码错误!!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

